package fr.norsys.mapper.console.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import fr.norsys.mapper.console.model.Attribute;
import fr.norsys.mapper.console.model.ConsoleCst;
import fr.norsys.mapper.console.model.Resource;
import fr.norsys.mapper.console.service.ApplicationService;
import fr.norsys.mapper.console.service.AttributeService;
import fr.norsys.mapper.console.service.ResourceService;

public class AttributeAction extends BaseAppDispatchAction {
	private static Log log = LogFactory.getLog(AttributeAction.class);

	private ApplicationService applicationService;

	private ResourceService resourceService;

	private AttributeService attributeService;

	AttributeAction() {
		super();
	}

	/**
	 * Get an attribute from the resource.
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("edit method called");
		}
		Resource currentResource = (Resource) request.getSession()
				.getAttribute(ConsoleCst.CURRENT_RESOURCE);
		String currentAttrId = (String) request
				.getParameter(ConsoleCst.CURRENT_ATTRIBUTE_ID);

		DynaActionForm attributeForm = (DynaActionForm) form;
		Attribute currentAttribute = new Attribute();
		if (currentAttrId != null && !"".equals(currentAttrId)) {

			currentAttribute = attributeService.get(currentAttrId,
					currentResource);
			if (log.isDebugEnabled()) {
				log.debug(currentAttribute);
			}
		}
		attributeForm.set(ConsoleCst.ATTRIBUTE_REQUEST_BEAN, currentAttribute);
		request.setAttribute(ConsoleCst.ATTRIBUTES_SESSION_BEAN,currentResource.getAttributes());
		request.getSession().setAttribute(ConsoleCst.CURRENT_ATTRIBUTE,
				currentAttribute);

		return mapping.findForward(ConsoleCst.ATTRIBUTE_PAGE_FORWARD);
	}

	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}

	public ApplicationService getApplicationService() {
		return applicationService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public ResourceService getResourceService() {
		return resourceService;
	}

	public AttributeService getAttributeService() {
		return attributeService;
	}

	public void setAttributeService(AttributeService attributeService) {
		this.attributeService = attributeService;
	}

}